# -*- coding: utf-8 -*-
import os

from global_data.constant_data import ConstantData
from global_data.glabal_data import GlobalData
from utils.file_utils import FileUtils
from utils.icloudp_log import IcloudpLog
from utils.sys_tools import SystemTools
from utils.time_utils import TimeUtils

log = IcloudpLog.get_logger_service()


class ServiceManage(object):

    # 检测服务
    @classmethod
    def check_service(cls, type="gateway"):
        if type == "gateway":
            name = GlobalData.SERVICE_GATEWAY_NAME
        else:
            name = GlobalData.SERVICE_WEB_NAME
        try:
            res = SystemTools.get_service_status(name)
            return True if res == 1 else False, ConstantData.SERVICE_STATUS.get(res)
        except Exception as e:
            log.error(f"检测服务失败: {e}")
            return False, f"异常: {e}"

    # 检测进程
    @classmethod
    def check_proce(cls, type="gateway"):
        if type == "gateway":
            name = GlobalData.SERVICE_GATEWAY_PROCE_NAME
        else:
            name = GlobalData.SERVICE_WEB_PROCE_NAME
        try:
            exist = SystemTools.process_exists(f"{name}.exe")
            return exist, "存在" if exist else "不存在"
        except Exception as e:
            log.error(f"检测进程失败: {e}")
            return False, f"异常: {e}"

    @classmethod
    def check(cls, type="gateway"):
        """
        检测服务 检测进程
        :param type:
        :return:
        """
        service_status, service_msg = ServiceManage.check_service(type)
        proce_status, proce_msg = ServiceManage.check_proce(type)
        status = False
        if service_status or proce_status:
            status = True
        if type == "gateway":
            msg = f"服务=【{service_msg}】， 进程={proce_msg}"
        else:
            msg = f"服务=【{service_msg}】"
        return status, msg

    # 停止服务
    @classmethod
    def stop_service(cls, type="gateway"):
        if type == "gateway":
            name = GlobalData.SERVICE_GATEWAY_NAME
        else:
            name = GlobalData.SERVICE_WEB_NAME
        try:
            SystemTools.stop_service(name)
            return True, "已停止"
        except Exception as e:
            log.error(f"停止服务失败: {e}")
            return False, f"异常: {e}"

    # 结束进程
    @classmethod
    def kill_process(cls, type="gateway"):
        if type == "gateway":
            name = GlobalData.SERVICE_GATEWAY_PROCE_NAME
        else:
            name = GlobalData.SERVICE_WEB_PROCE_NAME
        try:
            SystemTools.kill_proc(f"{name}.exe", True)
            return True, "已结束"
        except Exception as e:
            log.error(f"停止进程失败: {e}")
            return False, f"异常: {e}"

    # 结束
    @classmethod
    def stop(cls, type="gateway"):
        """
        停止服务 结束进程
        :param type:
        :return:
        """
        service_status, service_msg = ServiceManage.stop_service(type);
        proce_status, proce_msg = ServiceManage.kill_process(type);
        status = False
        if service_status and proce_status:
            status = True
        msg = f"服务=【{service_msg}】， 进程=【{proce_msg}】"
        return status, msg

    # 备份文件
    @classmethod
    def backup(cls, program_path, backup_path, type="gateway"):
        """
        1、创建备份目录
        2、检测程序路径
        3、拷贝文件
        :param type:
        :return:
        """
        try:
            if type == "gateway":
                program_path = FileUtils.join_path(program_path, "monSmartGateway")
                backup_path = FileUtils.join_path(backup_path, f"getway-{TimeUtils.get_current_datetime_string('%Y%m%d%H%M%S')}")
            else:
                program_path = FileUtils.join_path(program_path, "web")
                backup_path = FileUtils.join_path(backup_path, f"web-{TimeUtils.get_current_datetime_string('%Y%m%d%H%M%S')}")
            if not FileUtils.dir_exists(program_path):
                return False, "程序目录不存在，无法备份"
            msg = ""
            # 创建备份目录
            FileUtils.mkdirs(backup_path)
            # 拷贝文件
            if type == "gateway":
                if FileUtils.file_exists(FileUtils.join_path(program_path, "config", GlobalData.SERVICE_GATEWAY_SYSCONFIG)):
                    FileUtils.copy(FileUtils.join_path(program_path, "config", GlobalData.SERVICE_GATEWAY_SYSCONFIG), FileUtils.join_path(backup_path, GlobalData.SERVICE_GATEWAY_SYSCONFIG))
                    msg = f"{msg} 【{GlobalData.SERVICE_GATEWAY_SYSCONFIG}】已备份；"
                else:
                    msg = f"{msg} 【{GlobalData.SERVICE_GATEWAY_SYSCONFIG}】不存在；"
                if FileUtils.file_exists(FileUtils.join_path(program_path, "config", GlobalData.SERVICE_GATEWAY_SENDCONFIG)):
                    FileUtils.copy(FileUtils.join_path(program_path, "config", GlobalData.SERVICE_GATEWAY_SENDCONFIG), FileUtils.join_path(backup_path, GlobalData.SERVICE_GATEWAY_SENDCONFIG))
                    msg = f"{msg} 【{GlobalData.SERVICE_GATEWAY_SENDCONFIG}】已备份；"
                else:
                    msg = f"{msg} 【{GlobalData.SERVICE_GATEWAY_SENDCONFIG}】不存在；"
                if FileUtils.file_exists(FileUtils.join_path(program_path, "monSmartGateway.exe")):
                    FileUtils.copy(FileUtils.join_path(program_path, "monSmartGateway.exe"), FileUtils.join_path(backup_path, "monSmartGateway.exe"))
                    msg = f"{msg} 【monSmartGateway】已备份；"
                else:
                    msg = f"{msg} 【monSmartGateway】不存在；"
            else:
                if FileUtils.file_exists(FileUtils.join_path(program_path, "application-chengan.yml")):
                    FileUtils.copy(FileUtils.join_path(program_path, "application-chengan.yml"), FileUtils.join_path(backup_path, "application-chengan.yml"))
                    msg = f"{msg} 【application-chengan.yml】已备份；"
                else:
                    msg = f"{msg} 【application-chengan.yml】不存在；"
                if FileUtils.file_exists(FileUtils.join_path(program_path, "monitormanageweb.jar")):
                    FileUtils.copy(FileUtils.join_path(program_path, "monitormanageweb.jar"), FileUtils.join_path(backup_path, "monitormanageweb.jar"))
                    msg = f"{msg} 【monitormanageweb.jar】已备份；"
                else:
                    msg = f"{msg} 【monitormanageweb】不存在；"
            return True, "不存在文件，无需备份" if msg == "" else msg
        except Exception as e:
            log.error(f"备份失败: {e}")
            return False, f"备份异常: {e}"

    # 覆盖文件
    @classmethod
    def update(cls, program_path, file_path, type="gateway"):
        try:
            if type == "gateway":
                program_path = FileUtils.join_path(program_path, "monSmartGateway")
            else:
                program_path = FileUtils.join_path(program_path, "web")
            if not FileUtils.dir_exists(program_path):
                return False, "程序目录不存在，无法更新"
            msg = ""
            # 拷贝文件
            if type == "gateway":
                if FileUtils.file_exists(FileUtils.join_path(file_path, GlobalData.SERVICE_GATEWAY_SYSCONFIG)):
                    FileUtils.copy(FileUtils.join_path(file_path, GlobalData.SERVICE_GATEWAY_SYSCONFIG), FileUtils.join_path(program_path, "config", GlobalData.SERVICE_GATEWAY_SYSCONFIG))
                    msg = f"{msg} 【{GlobalData.SERVICE_GATEWAY_SYSCONFIG}】已更新；"
                else:
                    msg = f"{msg} 【{GlobalData.SERVICE_GATEWAY_SYSCONFIG}】不存在；"
                if FileUtils.file_exists(FileUtils.join_path(file_path, GlobalData.SERVICE_GATEWAY_SENDCONFIG)):
                    FileUtils.copy(FileUtils.join_path(file_path, GlobalData.SERVICE_GATEWAY_SENDCONFIG), FileUtils.join_path(program_path, "config", GlobalData.SERVICE_GATEWAY_SENDCONFIG))
                    msg = f"{msg} 【{GlobalData.SERVICE_GATEWAY_SENDCONFIG}】已更新；"
                else:
                    msg = f"{msg} 【{GlobalData.SERVICE_GATEWAY_SENDCONFIG}】不存在；"
                if FileUtils.file_exists(FileUtils.join_path(file_path, "monSmartGateway.exe")):
                    FileUtils.copy(FileUtils.join_path(file_path, "monSmartGateway.exe"), FileUtils.join_path(program_path, "monSmartGateway.exe"))
                    msg = f"{msg} 【monSmartGateway.exe】已更新；"
                else:
                    msg = f"{msg} 【monSmartGateway.exe】不存在；"
            else:
                if FileUtils.file_exists(FileUtils.join_path(file_path, "application-chengan.yml")):
                    FileUtils.copy(FileUtils.join_path(file_path, "application-chengan.yml"), FileUtils.join_path(program_path, "application-chengan.yml"))
                    msg = f"{msg} 【application-chengan.yml】已更新；"
                else:
                    msg = f"{msg} 【application-chengan.yml】不存在；"
                if FileUtils.file_exists(FileUtils.join_path(file_path, "monitormanageweb.jar")):
                    FileUtils.copy(FileUtils.join_path(file_path, "monitormanageweb.jar"), FileUtils.join_path(program_path, "monitormanageweb.jar"))
                    msg = f"{msg} 【monitormanageweb.jar】已更新；"
                else:
                    msg = f"{msg} 【monitormanageweb.jar】不存在；"
            return True, "不存在文件，无法更新" if msg == "" else msg
        except Exception as e:
            log.error(f"更新失败: {e}")
            return False, f"更新异常: {e}"

    # 启动服务
    @classmethod
    def start(cls, type="gateway"):
        if type == "gateway":
            name = GlobalData.SERVICE_GATEWAY_NAME
        else:
            name = GlobalData.SERVICE_WEB_NAME
        try:
            SystemTools.start_service(name)
            return True, "已启动"
        except Exception as e:
            log.error(f"启动服务失败: {e}")
            return False, f"启动服务异常: {e}"

    # 结束客户端进程
    @classmethod
    def kill_cs(cls):
        try:
            SystemTools.kill_proc(f"晟安立体库消防监控平台.exe", True)
            return True, "结束客户端进程成功"
        except Exception as e:
            log.error(f"结束客户端进程失败: {e}")
            return False, f"结束客户端进程失败: {e}"

    # 清理缓存
    @classmethod
    def clear_cache(cls):
        try:
            # rd /s /Q %APPDATA%\shengan-fire
            os.system("rd /s /Q %APPDATA%\shengan-fire");
            return True, "清理客户端缓存成功"
        except Exception as e:
            log.error(f"清理缓存失败: {e}")
            return False, f"清理缓存失败: {e}"

    # 重启客户端
    @classmethod
    def restart_cs(cls, path):
        try:
            FileUtils.start_file(path)
            return True, "启动客户端成功"
        except Exception as e:
            log.error(f"启动客户端程序失败: {e}")
            return False, f"启动客户端程序失败: {e}"

    # 重启客户端 并清理缓存
    @classmethod
    def clear_and_restart(cls, path):
        kill_status, kill_msg = ServiceManage.kill_cs()
        clear_status, clear_msg = ServiceManage.clear_cache()
        start_status, start_msg = ServiceManage.restart_cs(path)
        status = False
        msg = ""
        if kill_status and clear_status and start_status:
            status = True
        msg = f"{kill_msg}, {clear_msg}, {start_msg}"
        return status, msg


if __name__ == '__main__':
    print("Python")
